package backpage.controller;

import backpage.entity.AnnualLeave;
import backpage.entity.Employee;
import backpage.service.AnnualLeaveService;
import backpage.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@CrossOrigin
@RestController
@RequiredArgsConstructor
@RequestMapping("/leave")
public class AnnualLeaveController {

    @Autowired
    private AnnualLeaveService leaveService;

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private final SimpleDateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT);

    @PostMapping("/apply")
    public ResponseEntity<String> applyLeave(
            @RequestParam @NotNull(message = "员工ID不能为空") Integer employeeId,
            @RequestParam @NotNull(message = "审批人不能为空") Integer operator,
            @RequestParam String startDate,
            @RequestParam Integer daysLeave,
            @RequestParam(required = false) String remark
    ) {
        try{
            if (employeeId == null || operator == null) {
                return ResponseEntity
                        .badRequest()
                        .body("{\"code\":400, \"message\":\"员工ID和审批人不能为空\"}");
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false); // 关键：严格模式
            Date parsedDate;
            try {
                parsedDate = sdf.parse(startDate);
            } catch (ParseException e) {
                return ResponseEntity.badRequest()
                        .body("{\"code\":400, \"message\":\"日期格式错误，正确示例：2024-03-25\"}");
            }

            AnnualLeave record = new AnnualLeave();
            record.setOperator(operator);
            record.setEmployeeId(employeeId);
            record.setStartDataLeave(parsedDate);
            record.setDaysLeave(daysLeave);
            record.setDataApplyLeave(new Date());
            record.setStatus(0);
            record.setRemark(remark);

            leaveService.save(record);
            String jsonResponse = String.format(
                    "{\"code\":200, \"message\":\"success\", \"data\":%d}",
                    record.getRegistrationId()
            );
            return ResponseEntity.ok().body(jsonResponse);
        }catch (DateTimeParseException e) {
            return ResponseEntity
                    .badRequest()
                    .body("{\"code\":400, \"message\":\"日期格式错误，应为YYYY-MM-DD\"}");
        } catch (Exception e) {
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("{\"code\":500, \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    private final EmployeeService employeeService;

    @GetMapping("/records")
    public ResponseEntity<?> getRecords(
            @RequestParam Integer employeeId // 从请求参数获取当前用户ID
    ) {
        try {
            // 1. 获取当前用户完整信息
            Employee currentUser = employeeService.queryEmpInfoById(employeeId);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(errorResponse(401, "用户不存在"));
            }

            // 2. 执行查询
            List<AnnualLeave> records = leaveService.queryRecords(
                    currentUser.getEmployeeId(),
                    currentUser.getDepartmentId(),
                    currentUser.getRole()
            );

            // 3. 返回标准化响应
            return ResponseEntity.ok().body(successResponse(records));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse(500, e.getMessage()));
        }
    }

    // 响应构建方法（保持与原有风格一致）
    private Map<String, Object> successResponse(Object data) {
        return new LinkedHashMap<String, Object>(){{
            put("code", 200);
            put("message", "success");
            put("data", data);
        }};
    }

    private Map<String, Object> errorResponse(int code, String msg) {
        return new LinkedHashMap<String, Object>(){{
            put("code", code);
            put("message", msg);
        }};
    }

    @PutMapping("/process/{registrationId}")
    public ResponseEntity<?> processApplication(
            @PathVariable("registrationId") Long registrationId, // 参数名一致
            @RequestParam Integer status,
            @RequestParam Integer operatorId
    ) {
        try {
            // 1. 获取申请记录
            AnnualLeave record = leaveService.getById(registrationId);
            if (record == null) {
                return ResponseEntity.badRequest().body(errorResponse(404, "申请记录不存在"));
            }

            // 2. 权限校验
            if (!operatorId.equals(record.getOperator())) {
                return ResponseEntity.status(403).body(errorResponse(403, "无操作权限"));
            }

            // 3. 执行审批逻辑
            boolean success = leaveService.processApplication(registrationId, status, operatorId);
            return success ?
                    ResponseEntity.ok(successResponse(null)) :
                    ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse(500, "操作失败"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse(500, "服务器错误: " + e.getMessage()));
        }
    }

}

